import { BadRequestException, ForbiddenException, Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectRepository } from "@nestjs/typeorm";
import { pagination } from "src/common/pagination.query";
import { UploadHistoryQueryDto, UploadHistoryRemoveDto } from "src/dto/upload";
import { UploadHistoryEntity } from "src/entity";
import { UserService } from "src/user/service/user.service";
import { Repository } from "typeorm";

@Injectable()
export class UploadHistoryService {
    private readonly logger = new Logger(UploadHistoryService.name);

    constructor(
        @InjectRepository(UploadHistoryEntity) private readonly uploadRepository: Repository<UploadHistoryEntity>,
        private readonly userService: UserService,
        private readonly configService: ConfigService,
    ) {}

    query(id: number, dto: UploadHistoryQueryDto) {
        return pagination(this.uploadRepository.createQueryBuilder("upload").where("upload.user = :id", { id }), dto);
    }

    async add(id: number, uploadDto: { dir?: string; filename: string }) {
        const user = await this.userService.find(id);
        if (!user) {
            throw new ForbiddenException("用户不存在!");
        }
        this.logger.log(`requset add user: ${user.username}`);

        return await this.uploadRepository.save(
            this.uploadRepository.create({
                ...uploadDto,
                exist: true,
                user,
            }),
        );
    }

    async remove(id: number, dto: UploadHistoryRemoveDto) {
        this.logger.log(`requset remove user id: ${id} dto id: ${dto.id}`);

        const result = await this.uploadRepository.delete({
            id: dto.id,
            user: {
                id,
            },
        });
        if (result.affected == 0) throw new BadRequestException("删除失败");
    }
}
